package com.lzj.gen.jetbrains;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

/**
 * Created by lzj on 2023/11/24
 */
public class PemUtil {

    public static void saveToPemFile(String outputPath, String type, byte[] data) throws IOException {
        PemObject pemObject = new PemObject(type, data);
        FileWriter fileWriter = new FileWriter(outputPath);
        PemWriter pemWriter = new PemWriter(fileWriter);
        pemWriter.writeObject(pemObject);
        pemWriter.close();
    }

    public static byte[] readPem(String outputPath) throws IOException {
        PemReader pemReader = new PemReader(new FileReader(outputPath));
        PemObject pemObject = pemReader.readPemObject();
        return pemObject.getContent();
    }

    public static String readPemFullStr(String outputPath) throws IOException {
        PemReader pemReader = new PemReader(new FileReader(outputPath));
        PemObject pemObject = pemReader.readPemObject();
        StringWriter stringWriter = new StringWriter();
        PemWriter pemWriter = new PemWriter(stringWriter);
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        return stringWriter.toString();
    }
}
